﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using PopcornBTMonitor.Config;

namespace PopcornBTMonitor.Command
{
    public class TorrentUploader
    {
        #region Properties
        public string Address{ get; private set; }
        #endregion

        #region Public Methods
        public TorrentUploader()
        {
            this.Address = Config.ConfigSettings.PCHAddress;
        }

        //----------------------------------------------------------------------

        public bool UploadTorrent(string torrent)
        {
            if (File.Exists(torrent))
            {
                WebClient client = new WebClient();
                client.Headers.Add("Content-Type", "applicatin/x-bittorrent");
                client.Headers.Add("Content-Disposition", "form-data; name=\"upfile\"; filename=\"" + Path.GetFileName(torrent) + "\"");
                try
                {
                    byte[] response = client.UploadFile(this.Address, "POST", torrent);
                    string responseStr = System.Text.ASCIIEncoding.ASCII.GetString(response);
                    return CheckResponse(responseStr);
                }
                catch
                {
                    return false;
                }
                
            }
            else
            {                
                return false;
            }
        }
        #endregion

        #region Protected Methods
        protected bool CheckResponse(string response)
        {
            return Regex.Match(response, @"<title>\s*Torrent Service Message\s*</title>", RegexOptions.IgnoreCase).Success;
        }
        #endregion

    }
}
